#include <rclcpp/rclcpp.hpp>

#include <thread>

#include "mainwindow.h"

#include <QApplication>
#include <QLocale>
#include <QTranslator>

#include "node/node.h" // ros2 app

static void signalHandler(int signum) {
    rclcpp::shutdown();
    QApplication::quit();
}

int main(int argc, char *argv[]) {
    signal(SIGINT, signalHandler);  // 捕获 Ctrl+C 信号
    signal(SIGTERM, signalHandler); // 捕获 kill 信号

    std::shared_ptr<AppNode> appNode = std::make_shared<AppNode>("app_node");

    rclcpp::init(argc, argv);
    std::thread ros2_thread([appNode]() { rclcpp::spin(appNode); });

    QApplication a(argc, argv);

    QTranslator translator;
    const QStringList uiLanguages = QLocale::system().uiLanguages();
    for (const QString &locale : uiLanguages) {
        const QString baseName = "mbot-app_" + QLocale(locale).name();
        if (translator.load(":/i18n/" + baseName)) {
            a.installTranslator(&translator);
            break;
        }
    }

    MainWindow w{appNode};
    w.show();
    a.exec();

    rclcpp::shutdown();

    if (ros2_thread.joinable()) {
        ros2_thread.join();
    }

    return 0;
}
